<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<form id="form">
			<input type="text" name="name" placeholder="书本名称" /></br>
			<input type="text" name="price" placeholder="单价" /></br>
			<input type="date" name="tdate" placeholder="出版日期" /></br>
			<button type="button" onclick="save()">保存</button>
		</form>
		<script src="../js/jquery-3.5.1.min.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			// //判断是添加还是编辑
			let name = sessionStorage.getItem("index");
			let editItem = null;
			if(name) {
				$.get("http://localhost:8080/list?name=" + name, function(result) {
					console.log(result);
					if(result instanceof Array && result.length > 0) {
						editItem = result[0]
						$("input[name='name']").val(editItem.name);
						$("input[name='price']").val(editItem.price);
						$("input[name='tdate']").val(editItem.date);
					}
				});
			}

			function save() {
				let name = $("input[name='name']").val();
				let price = $("input[name='price']").val();
				let tdate = $("input[name='tdate']").val();
				//课堂作业：实现id的自增长。当前书id的最大+1
				let obj = {
					id: editItem ? editItem.id : 1,
					name: name,
					price: price,
					date: tdate,
					count: editItem ? editItem.count : 1,
				}

				if (editItem) {
					$.post("http://localhost:8080/edit", obj, function(result) {
						console.log(result);
					});
				} else {
					$.post("http://localhost:8080/add", obj, function(result) {
						console.log(result);
					});
				}

				//页面跳转
				location.href = 'Ajax访问后台.html';
			}
		</script>
	</body>
</html>